/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;

namespace Xceed.Silverlight.Data.Stats
{
  public class GeometricMeanFunction : CumulativeStatFunction
  {
    public GeometricMeanFunction()
      : base()
    {
    }

    public GeometricMeanFunction( string resultPropertyName, string sourcePropertyName )
      : base( resultPropertyName, sourcePropertyName )
    {
    }

    #region PrerequisiteFunctions Property

    protected internal override StatFunction[] PrerequisiteFunctions
    {
      get
      {
        StatFunction[] prerequisites = m_prerequisites;

        if( prerequisites == null )
        {
          prerequisites = new StatFunction[]
          {
            new CountFunction( "GeometricMeanFunction.Count", this.SourcePropertyName )
          };

          if( this.IsSealed )
            m_prerequisites = prerequisites;
        }

        return prerequisites;
      }
    }

    #endregion PrerequisiteFunctions Property

    protected internal override void Validate()
    {
      base.Validate();
      base.ValidateSourcePropertyName( 1 );
    }

    protected override void Initialize( Type[] sourcePropertyTypes )
    {
      base.Initialize( sourcePropertyTypes );

      switch( Type.GetTypeCode( sourcePropertyTypes[ 0 ] ) )
      {
        case TypeCode.Char:
        case TypeCode.Byte:
        case TypeCode.SByte:
        case TypeCode.Int16:
        case TypeCode.Int32:
        case TypeCode.Int64:
        case TypeCode.UInt16:
        case TypeCode.UInt32:
        case TypeCode.UInt64:
          m_accumulationType = TypeCode.UInt64;
          break;

        case TypeCode.Single:
        case TypeCode.Double:
          m_accumulationType = TypeCode.Double;
          break;

        case TypeCode.Decimal:
          m_accumulationType = TypeCode.Decimal;
          break;
      }
    }

    protected internal override void InitializePrerequisites( StatResult[] prerequisitesValues )
    {
      if( prerequisitesValues.Length != 1 )
        throw new ArgumentException( "The prerequisite initializers do not match the PrerequisiteFunctions." );

      checked
      {
        m_count = Convert.ToInt64( prerequisitesValues[ 0 ].Value );

        if( m_count == 0 )
        {
          // No need to go further (i.e. Accumulate), the result cannot be calculated.
          throw new DivideByZeroException();
        }
      }
    }

    protected internal override void Reset()
    {
      m_ulongProduct = 1;
      m_doubleProduct = 1d;
      m_decimalProduct = 1m;
      m_count = 0;
    }

    protected internal override void Accumulate( object[] values )
    {
      if( StatFunction.CanProcessValues( values, 1 ) )
      {
        checked
        {
          switch( m_accumulationType )
          {
            case TypeCode.UInt64:
              {
                ulong number = Convert.ToUInt64( values[ 0 ] );

                if( number > 0 )
                {
                  m_ulongProduct *= number;
                }
                else
                {
                  throw new InvalidValueException( "The geometric mean can only be calculated on elements whose values are greater than zero." );
                }
              }
              break;

            case TypeCode.Double:
              {
                double number = Convert.ToDouble( values[ 0 ] );

                if( number > 0d )
                {
                  m_doubleProduct *= number;
                }
                else
                {
                  throw new InvalidValueException( "The geometric mean can only be calculated on elements whose values are greater than zero." );
                }
              }
              break;

            case TypeCode.Decimal:
              {
                decimal number = Convert.ToDecimal( values[ 0 ] );

                if( number > 0m )
                {
                  m_decimalProduct *= number;
                }
                else
                {
                  throw new InvalidValueException( "The geometric mean can only be calculated on elements whose values are greater than zero." );
                }
              }
              break;
          }
        }
      }
    }

    protected internal override void AccumulateChildResult( StatResult childResult )
    {
      GeometricMeanResult geoMeanResult = ( GeometricMeanResult )childResult;

      checked
      {
        switch( m_accumulationType )
        {
          case TypeCode.UInt64:
            m_ulongProduct *= Convert.ToUInt64( geoMeanResult.Product );
            break;

          case TypeCode.Double:
            m_doubleProduct *= Convert.ToDouble( geoMeanResult.Product );
            break;

          case TypeCode.Decimal:
            m_decimalProduct *= Convert.ToDecimal( geoMeanResult.Product );
            break;
        }
      }
    }

    protected internal override StatResult GetResult()
    {
      object result = null;
      object product = null;

      checked
      {
        switch( m_accumulationType )
        {
          case TypeCode.UInt64:
            product = m_ulongProduct;
            result = Math.Pow( Convert.ToDouble( m_ulongProduct ), 1d / m_count );
            break;

          case TypeCode.Double:
            product = m_doubleProduct;
            result = Math.Pow( m_doubleProduct, 1d / m_count );
            break;

          case TypeCode.Decimal:
            product = m_decimalProduct;
            result = Math.Pow( Convert.ToDouble( m_decimalProduct ), 1d / m_count );
            break;
        }
      }

      return new GeometricMeanResult( result, product );
    }

    private TypeCode m_accumulationType = TypeCode.Empty;
    private StatFunction[] m_prerequisites;
    private long m_count;
    private ulong m_ulongProduct;
    private double m_doubleProduct;
    private decimal m_decimalProduct;

    private class GeometricMeanResult : StatResult
    {
      public GeometricMeanResult( object value, object product )
        : base( value )
      {
        m_product = product;
      }

      #region Product property

      public object Product
      {
        get
        {
          return m_product;
        }
      }

      private object m_product;

      #endregion
    }
  }
}
